var Model = require("../../../model/Model");
module.exports = function(app) {
    return new roomRemote(app);
};
var roomRemote = function(app) {
    this.app = app;
    this.channelService = app.get("channelService");
};
roomRemote.prototype.enterRoom = function(uid, roomId, sid , cb) {   
    console.log("roomRemote.prototype.enterRoom") ;   
    var channel = this.channelService.getChannel(roomId, true);
    if (!Model.room[roomId]) {
        Model.room[roomId] = {  
            roomId:roomId,
            status:0,
            playerCount:1,
            player:[{
                uid:uid,
                prepare:false
            }, null, null, null]
        };
    } else {
        for(var i = 0; i < Model.room[roomId].player.length; i++) {
            if (Model.room[roomId].player[i] === null) {
                Model.room[roomId].player[i] = {
                    uid:uid,
                    prepare:false
                };
                Model.room[roomId].playerCount ++;
                channel.pushMessage("push", {data:{model:[
                    {key:"model.room.player.[" + i + "]", value:Model.room[roomId].player[i]},
                    {key:"model.room.playerCount", value:Model.room[roomId].playerCount},
                ]}});
                break;
            }
        }
    }
    channel.add(uid, sid);

    cb(Model.room[roomId]);
};
roomRemote.prototype.exitRoom = function(uid, roomId, sid , cb) {  
    console.log("roomRemote.prototype.exitRoom") ; 
    var channel = this.channelService.getChannel(roomId, true);
    if (!!channel) {
        channel.leave(uid, sid);
    }
    for(var i = 0; i < Model.room[roomId].player.length; i++) {
        if (Model.room[roomId].player[i] !== null && Model.room[roomId].player[i].uid === uid) {
            Model.room[roomId].player[i] = null;
            Model.room[roomId].playerCount --;
            channel.pushMessage("push", {data:{model:[
                {key:"model.room.player.[" + i + "]", value:null},
                {key:"model.room.playerCount", value:Model.room[roomId].playerCount},
            ]}});
            break;
        }
    }
    if (cb) {
        cb();
    }
};